<?php
/**
 * Created by PhpStorm.
 * User: 王柯 <wangke.email@foxmail.com>
 * Date: 2018\4\28 0028
 * Time: 15:23
 */
namespace app\common\lib\wechat;

class WxCommon{
    /**
     * 获取配置银行编号
     * @param string $bank_name 银行名称（如：建设银行） *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void|int|string 配置银行编号
     */
    public static function getBankCode($bank_name){
        foreach(config('bank') as $key => $val){
            if(in_array($bank_name,config('bank'))){
                if(config('bank')[$key] == $bank_name){
                    return $key;
                }
            }
        }
    }

    /**
     * 微信用户提现手续费算法
     * @param int $total_amount 用户提现金额 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return float|int
     */
    public static function wxWithdrawalsServiceCost($total_amount){
        if($total_amount >= 1 && $total_amount <= 100000){
            return 100;
        }elseif($total_amount > 100000 && $total_amount <= 2500000){
            return is_float($total_amount * 0.001) ? floor($total_amount * 0.001) : $total_amount * 0.001;
        }else{
            return 2500;
        }
    }

    /**
     * 微信rsa字段加密
     * @param string $input 需要加密的字段值 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string
     */
    public static function rsaEncrypt($input)
    {
        //读取公钥内容 $pub_key = openssl_pkey_get_public(file_get_contents(路径地址));
        $pub_key = openssl_pkey_get_public(file_get_contents(EXTEND_PATH.'/wxpay/cert/wx_public_key.pem'));//halt($pub_key);
        //halt(openssl_pkey_get_details($pub_key));

        //读取私钥内容 $pri_key = openssl_pkey_get_private(file_get_contents(路径地址));
        $pri_key = openssl_get_privatekey(file_get_contents(EXTEND_PATH.'/wxpay/cert/apiclient_key.pem'));

        //加密
        $encryptData = '';

        //解密（暂不需要）
        $decryptData = '';

        //公钥加密 用标准的RSA加密库对敏感信息进行加密，选择RSA_PKCS1_OAEP_PADDING填充模式（eg：Java的填充方式要选 " RSA/ECB/OAEPWITHSHA-1ANDMGF1PADDING"）
        openssl_public_encrypt($input,$encryptData,$pub_key,OPENSSL_PKCS1_OAEP_PADDING);

        //得到进行rsa加密并转base64之后的密文
        $result = base64_encode($encryptData);//halt($result);//halt($encryptData);

        //私钥解密
        openssl_private_decrypt(base64_decode($encryptData),$decryptData,$pri_key);//halt($decryptData);

        return $result;
    }

    /**
     * 获取微信公钥 请求方式:POST
     * @param string $url 请求Url https://fraud.mch.weixin.qq.com/risk/getpublickey
     * @param string mch_id 商户号
     * @param string nonce_str 随机字符串
     * @param string sign 签名
     * @param string sign_type 签名类型 MD5
     * @author 王柯 <wangke.email@foxmail.com>
     * @return mixed
     */
    public static function getWxPublicKey(){
        //请求Url
        $url = 'https://fraud.mch.weixin.qq.com/risk/getpublickey';

        //商户号
        $data['mch_id'] = config('wxpay.merchant_id');

        //随机字符串
        $data['nonce_str'] = self::makeNonceStr(32);

        //签名类型
        $data['sign_type'] = 'MD5';

        //签名
        $data['sign'] = self::makeSign($data);

        //数组转xml
        $xml = self::arrayToXml($data);

        //cul请求获取公钥
        $public_key_array = curlRequest($url,$xml,'post',true);

        //xml转数组
        $array = self::xmlToArray($public_key_array);

        return $array['pub_key'];
    }

    /**
     * 生成签名
     * @param array $params 需要生成签名的数组 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string 签名
     */
    public static function makeSign($params){
        //按字典序排序数组参数
        ksort($params);

        //拼接参数
        $string = self::toUrlParams($params);

        //在string后加入key
        $string = $string.'&key='.config('wxpay.key');

        //md5加密
        $string = md5($string);

        //所有字符转为大写
        $result = strtoupper($string);

        return $result;
    }

    /**
     * 转换url参数 将参数拼接为url: key=value&key=value
     * @param $params *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string
     */
    public static function toUrlParams($params){
        $string = '';
        if(!empty($params)){
            $array = array();
            foreach($params as $key => $value){
                $array[] = $key.'='.$value;
            }
            $string = implode("&",$array);
        }
        return $string;
    }

    /**
     * 生成随机字符串
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string
     */
    public static function makeNonceStr($length = 32){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = '';
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }

    /**
     * 数组转xml
     * @param array $arr 数组参数 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return string
     */
    public static function arrayToXml($arr){
        $xml = "<xml>";

        foreach($arr as $key => $val){
            if(is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }

        $xml.="</xml>";

        return $xml;
    }

    /**
     * xml转数组
     * @param string $xml xml数据 *必传
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|bool|\mix|mixed|\stdClass|string
     */
    public static function xmlToArray($xml){
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);

        return $array_data;
    }

    /**
     * 获取ip地址
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array|false|string
     */
    public static function getClientIp(){
        if ($_SERVER['REMOTE_ADDR']) {
            $client_ip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $client_ip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $client_ip = getenv("HTTP_CLIENT_IP");
        } else {
            $client_ip = "unknown";
        }
        return $client_ip;
    }
}
